# @Author: huguangzhi
# @design: E480
# @ContactEmail : huguangzhi@ucsdigital.com.com
# @ContactPhone : 13121961510
# @Desc  :
from __future__ import print_function

import time

import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_tcp, hooks
import logging

from modbus_tk.exceptions import ModbusError


class modbus_master():

    def __init__(self, address="localhost", port=502, timeout=150.0, log_level=logging.DEBUG):
        # 通过自带的工具来创建日志的种类和级别
        # 共有三种，一种直接发邮件的，一种在console中显示，一种通过UDP来进行数据发送的
        self.logger = modbus_tk.utils.create_logger("console", level=log_level)
        self.ip_address = address
        self.port = port
        self.connect_timeout = timeout
        # 建立历史数据接收
        hooks.install_hook("modbus.Master.after_recv", self.on_after_recv)
        hooks.install_hook("modbus_tcp.Master.before_connect", self.on_before_connect)
        hooks.install_hook("modbus_tcp.Master.after_recv", self.on_before_connect)

    def on_after_recv(self, data):
        master, bytearray_data = data
        # print([item for item in bytearray_data])
        # self.logger.DEBUG([item for item in bytearray_data])

    def on_before_connect(self, master):
        self.logger.DEBUG("on_before_connect {0} {1}".format(master._host, master._port))

    def on_after_recv2(self, data):
        self.logger.debug("on_after_recv2 {0} bytes received".format(len(data)))

    def tcp_connect_slave(self):
        # Connect to the slave
        master = modbus_tcp.TcpMaster(host=self.ip_address, port=self.port, timeout_in_sec=self.connect_timeout)
        self.logger.info("connected to TCP")
        return master

    def get_slave_data(self, slave_ID: int, start_address: int, size: int, master=None):
        if master is None:
            master = self.tcp_connect_slave()
        receve = master.execute(slave_ID, cst.READ_HOLDING_REGISTERS, start_address, size)
        # receve = master.execute(slave_ID, cst.READ_INPUT_REGISTERS, start_address, size)
        # receve = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 10)
        # 这个格式我是真的看不懂 地址在这里https://docs.python.org/zh-cn/3.6/library/struct.html?highlight=struct%20format#format-characters
        self.logger.info(master.execute(0, cst.READ_HOLDING_REGISTERS, 65, 2))
        self.logger.info(receve)
        return receve



if __name__ == "__main__":
    slave_ID = 0
    start_address = 64
    size = 2
    modbus_master_1 = modbus_master(address="10.171.28.31",port=8787, timeout=3000)
    master_info = modbus_master_1.tcp_connect_slave()
    while True:
        # receved_data = modbus_master_1.get_slave_data(master=master_info, slave_ID=slave_ID,start_address=start_address,size=size)
        # receved_data2 = modbus_master_1.get_slave_data(master=master_info, slave_ID=2,start_address=start_address,size=size)
        receved_data2 = modbus_master_1.get_slave_data(master=master_info, slave_ID=0,start_address=start_address,size=size)
        print(receved_data2)
        time.sleep(1)